import { Component, OnDestroy, OnInit } from '@angular/core';
import { NzCascaderOption } from 'ng-zorro-antd';
import { EzFormComponent } from '../ez-form';
import { EzFormControlComponent } from '../ez-form-control';
import { EzFormGroupComponent } from '../ez-form-group';
import { EzFormItemComponent } from '../ez-form-item';
import { EzCascader } from './ez-cascader';
import { EzCascaderConfiguration, EzCascaderOption } from './ez-cascader.configuration';
import { of } from 'rxjs';

@Component({
  selector: 'ez-cascader',
  templateUrl: './ez-cascader.component.html',
  styleUrls: ['./ez-cascader.component.less'],
  providers: [{ provide: EzFormControlComponent, useExisting: EzCascaderComponent }],
})
export class EzCascaderComponent extends EzFormControlComponent<EzCascaderConfiguration, (string | number)[]>
  implements EzCascader, OnInit, OnDestroy {
  constructor(
    protected ezForm: EzFormComponent,
    protected ezFormGroup: EzFormGroupComponent,
    protected ezFormItem: EzFormItemComponent
  ) {
    super(ezForm, ezFormGroup, ezFormItem);
  }

  ngOnInit(): void {
    super.ngOnInit();
  }

  ngOnDestroy(): void {
    super.ngOnDestroy();
  }

  checkConfiguration(configuration: EzCascaderConfiguration): void {}

  loadData: (option: EzCascaderOption, index: number) => PromiseLike<void> = (option, index) => {
    return new Promise((resolve, reject) => {
      if (Array.isArray(this.ezFormControlConfiguration.options)) {
        if (index < 0) {
          option.children = this.ezFormControlConfiguration.options;
        }
        resolve();
      } else if (this.ezFormControlConfiguration.options instanceof Function) {
        this.ezFormControlConfiguration.options(option, index, this, this.ezFormGroup, this.ezForm).then(
          children => {
            if (children && children.length > 0) {
              option.children = children;
            }
            resolve();
          },
          () => {
            reject();
          }
        );
      } else {
        resolve();
      }
    });
  };
}
